﻿using System.Windows;
using System.Windows.Controls;
using System.Windows.Media;

namespace Bravura.Editing.Common.Controls
{
	/// <summary>
	/// A canvas with a a grid drawn on it.
	/// </summary>
	public class GridCanvas : Canvas
	{
		#region Properties

		public double GridLeft
		{
			get;
			set;
		}

		public double GridTop
		{
			get;
			set;
		}

		public double GridWidth
		{
			get;
			set;
		}

		public double GridHeight
		{
			get;
			set;
		}

		public Color GridColor
		{
			get;
			set;
		}

		#endregion

		public GridCanvas()
		{
			this.GridLeft = 20.0;
			this.GridTop = 20.0;
			this.GridWidth = 80.0;
			this.GridHeight = 80.0;
			this.Background = new SolidColorBrush(Color.FromRgb(0xE0, 0xE0, 0xF8));
			this.GridColor = Color.FromArgb(85, 15, 15, 15);
		}

		#region Methods

		public void PlaceChild(int x, int y, Control child)
		{
			// add if not added
			if (!this.Children.Contains(child))
			{
				this.Children.Add(child);
			}

			// position
			Thickness margin = child.Margin;
			margin.Left = this.GridLeft + x * this.GridWidth;
			margin.Top = this.GridTop + y * this.GridHeight;
			child.Margin = margin;

			// size
			child.Width = this.GridWidth;
			child.Height = this.GridHeight;
		}

		protected override void OnRender(DrawingContext dc)
		{
			base.OnRender(dc);

			Pen pen = new Pen(new SolidColorBrush(GridColor), 1.0);
			Point p0 = new Point(0.0, 0.0);
			Point p1 = new Point(0.0, 0.0);

			// draw vertical lines
			p0.X = GridLeft;
			p0.Y = 0.0;
			p1.X = GridLeft;
			p1.Y = this.ActualHeight + 1.0;
			for (double x = GridLeft; x < this.ActualWidth; x += GridWidth)
			{
				p0.X = x;
				p1.X = x;
				dc.DrawLine(pen, p0, p1);
			}

			// draw horizontal lines
			p0.X = 0.0;
			p0.Y = GridTop;
			p1.X = this.ActualWidth + 1.0;
			p1.Y = GridTop;
			for (double y = GridTop; y < this.ActualHeight; y += GridHeight)
			{
				p0.Y = y;
				p1.Y = y;
				dc.DrawLine(pen, p0, p1);
			}
		}

		#endregion
	}
}
